<script setup lang="ts">
import { ref } from 'vue'
import { getAuthListApi, addAuthApi } from '@/apis/auth'
import type { getAuthApi } from '@/types/auth'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
const router = useRouter()

// 所有的权限列表
const authList = ref([] as getAuthApi[])
const getAuthList = async () => {
  const res = await getAuthListApi()
  authList.value = res.data.data as getAuthApi[]
}
getAuthList()

const formData = ref({
  auth_name: '',
  type: 1,
  path: '',
  keep_alive: 0,
  component: '',
  pid: 0,
})

// 新增
const addAuth = async () => {
  const res = await addAuthApi(formData.value)
  if (res.data.state !== 201) {
    return ElMessage.error(res.data.msg)
  }

  ElMessage.success('添加权限成功')
  router.push('/auth')
}
</script>

<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span>权限创建</span>
      </div>
    </template>

    <!-- 表单 -->
    <el-form :model="formData" label-width="auto">
      <el-form-item label="权限名称">
        <el-input placeholder="请输入权限名称" v-model="formData.auth_name"></el-input>
      </el-form-item>
      <el-form-item label="种类">
        <el-radio-group v-model="formData.type">
          <el-radio :value="1" size="default" border>菜单</el-radio>
          <el-radio :value="2" size="default" border>按钮</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="路由路径" v-if="formData.type === 1">
        <el-input placeholder="请输入路由" v-model="formData.path"></el-input>
      </el-form-item>

      <el-form-item label="组件缓存" v-if="formData.type === 1">
        <el-switch
          v-model="formData.keep_alive"
          width="60"
          inline-prompt
          active-text="已缓存"
          inactive-text="未缓存"
          :active-value="1"
          :inactive-value="0"
          style="--el-switch-on-color: #71e2a3; --el-switch-off-color: #fb8f90"
        />
      </el-form-item>

      <el-form-item label="组件路径" v-if="formData.type === 1">
        <el-input placeholder="请输入组件路径" v-model="formData.component"></el-input>
      </el-form-item>

      <el-form-item label="所属权限">
        <el-select v-model="formData.pid" size="large" style="width: 240px">
          <el-option label="顶级权限" :value="0" />
          <el-option
            v-for="item in authList"
            :key="item.auth_id"
            :label="item.auth_name"
            :value="item.auth_id"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="addAuth">新增权限</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style scoped lang="scss"></style>
